<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="科研经费编号" prop="fundingId">
        <el-input
          v-model="queryParams.fundingId"
          placeholder="请输入科研经费编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

          <el-form-item label="资金来源" prop="name" >
             <el-select v-model="queryParams.sourceId" placeholder="请选择资金来源"
             clearable
              @change="handleQuery">
                <el-option
                  v-for="item in sourceOptions"
                  :key="item.sourceId"
                  :label="item.sourceName"
                  :value="item.sourceId"
                ></el-option>
              </el-select>
          </el-form-item>

      <el-form-item label="拨款金额" prop="allocationAmount">
        <el-input
          v-model="queryParams.allocationAmount"
          placeholder="请输入拨款金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="拨款日期" prop="allocationDate">
        <el-date-picker clearable
          v-model="queryParams.allocationDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择拨款日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="审核状态" prop="status">
  <el-select
    v-model="queryParams.status"
    placeholder="请选择审核状态"
    clearable
    @change="handleQuery"
  >
    <el-option label="未提交" value="0"></el-option>
    <el-option label="待审核" value="1"></el-option>
    <el-option label="打回修改" value="2"></el-option>
    <el-option label="未通过" value="3"></el-option>
    <el-option label="已通过" value="4"></el-option>
  </el-select>
</el-form-item>


      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['funding:allocation:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['funding:allocation:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['funding:allocation:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['funding:allocation:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="allocationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="拨款记录" align="center" prop="allocationId" />
      <el-table-column label="科研经费编号" align="center" prop="fundingId" />

      <el-table-column label="资金来源" align="center" prop="sourceName" />

      <el-table-column label="拨款金额" align="center" prop="allocationAmount" />
      <el-table-column label="拨款日期" align="center" prop="allocationDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.allocationDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用途描述" align="center" prop="purpose" />

      <el-table-column label="拨款文件" align="center">
  <template slot-scope="scope">
    <template v-if="scope.row.files">
      <div v-for="(file, index) in scope.row.files.split(',')" :key="index">
        <a
          :href="file.trim()"
          target="_blank"
          style="color: #409EFF; text-decoration: underline;"
        >
          查看文件 {{ index + 1 }}
        </a>
      </div>
    </template>
    <span v-else>无文件</span>
  </template>
</el-table-column>

<el-table-column label="创建时间" align="center" prop="createTime" />
<el-table-column label="更新时间" align="center" prop="updateTime" />

      <el-table-column prop="status" label="审核状态" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.funding_status" :value="scope.row.status"/>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['funding:allocation:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['funding:allocation:remove']"
          >删除</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleHistory(scope.row)"
            v-hasPermi="['funding:allocation:history']"
          >查看历史记录</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改资金拨款记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="科研经费编号" prop="fundingId">
          <el-input v-model="form.fundingId" placeholder="请输入科研经费编号" />
        </el-form-item>

       <el-form-item label="资金来源">
             <el-select v-model="form.sourceId" placeholder="请选择资金来源">
                <el-option
                  v-for="item in sourceOptions"
                  :key="item.sourceId"
                  :label="item.sourceName"
                  :value="item.sourceId"
                ></el-option>
              </el-select>
        </el-form-item>

        <el-form-item label="拨款金额" prop="allocationAmount">
          <el-input v-model="form.allocationAmount" placeholder="请输入拨款金额" />
        </el-form-item>
        <el-form-item label="拨款日期" prop="allocationDate">
          <el-date-picker clearable
            v-model="form.allocationDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择拨款日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="用途描述" prop="purpose">
          <el-input v-model="form.purpose" placeholder="请输入用途描述" />
        </el-form-item>
        <el-form-item label="拨款文件" prop="files">
         <FileUpload v-model="form.files"/>
        </el-form-item>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  <el-dialog
    title="历史记录"
    :visible.sync="historyDialogVisible"
    width="80%"
    custom-class="custom-dialog"
  >
    <el-table
      :data="historyList"
      style="width: 100%"
      header-cell-class-name="table-header"
      cell-class-name="table-cell"
    >
      <el-table-column type="index" label="记录编号" ></el-table-column>
      <el-table-column prop="historyType" label="操作类型"></el-table-column>
      <el-table-column prop="createBy" label="添加人"></el-table-column>
      <el-table-column prop="updateBy" label="修改人"></el-table-column>
      <el-table-column prop="createTime" label="操作时间"></el-table-column>
      <el-table-column prop="fundingId" label="经费编号"></el-table-column>
      <el-table-column prop="sourceName" label="资金来源"></el-table-column>
      <el-table-column prop="allocationAmount" label="拨款金额"></el-table-column>
      <el-table-column prop="allocationDate" label="拨款日期"></el-table-column>
      <el-table-column prop="purpose" label="用途描述"></el-table-column>

      <el-table-column label="拨款文件" align="center" width="100">
        <template slot-scope="scope">
          <template v-if="scope.row.files">
            <div v-for="(file, index) in scope.row.files.split(',')" :key="index">
              <a
                :href="file.trim()"
                target="_blank"
                class="file-link"
              >
                查看文件 {{ index + 1 }}
              </a>
            </div>
          </template>
          <span v-else>无文件</span>
        </template>
      </el-table-column>

      <el-table-column prop="status" label="审核状态" width="75">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.funding_status" :value="scope.row.status"/>
        </template>
      </el-table-column>

<el-table-column label="操作" align="center" width="120">
    <template slot-scope="scope">
        
        <!-- <el-button
            v-if="hasPermission('funding:restore')"
            type="text"
            :loading="scope.row.loading"
            @click="restoreRow(scope.row)"
        > -->
        <el-button
            type="text"
            :loading="scope.row.loading" 
            @click="restoreRow(scope.row)" 
        >
            <i class="el-icon-refresh"></i> 
            <span>还原</span>
        </el-button>
    </template>
</el-table-column>

      <!-- 其他列根据需要添加 -->
    </el-table>
    <span slot="footer" class="dialog-footer">
      <el-button @click="historyDialogVisible = false" class="close-button">关闭</el-button>
    </span>
  </el-dialog>


  </div>
</template>

<script>
import { listAllocation, getAllocation, delAllocation, addAllocation, updateAllocation,getAllocationHistory,restoreData } from "@/api/funding/allocation";
import { getAllSource } from "@/api/funding/source";


export default {
  name: "Allocation",
  dicts: ["funding_status"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 资金拨款记录表格数据
      allocationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //资金来源
      sourceOptions:[],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fundingId: null,
        sourceId: null,
        allocationAmount: null,
        allocationDate: null,
        purpose: null,
        files: null,
        deleteBy: null,
        deleteTime: null,
        version: null,
        flowInstantId: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 历史记录对话框显示
      historyDialogVisible: false, // 添加这一行
      // 历史记录列表
      historyList: []
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询资金拨款记录列表 */
    getList() {
      this.loading = true;
      listAllocation(this.queryParams).then(response => {
        this.allocationList = response.rows;
        this.total = response.total;
        this.loading = false;

      getAllSource().then(
        response=>{
         
          this.sourceOptions=response.data;
        }
      );

      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        allocationId: null,
        fundingId: null,
        sourceId: null,
        allocationAmount: null,
        allocationDate: null,
        purpose: null,
        files: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        deleteBy: null,
        deleteTime: null,
        delFlag: null,
        version: null,
        flowInstantId: null,
        status: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.allocationId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加资金拨款记录";

      getAllSource().then(
        response=>{

          this.sourceOptions=response.data;
        }
      );

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const allocationId = row.allocationId || this.ids
      getAllocation(allocationId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改资金拨款记录";
      });

      getAllSource().then(
        response=>{

          this.sourceOptions=response.data;
        }
      );

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.allocationId != null) {
            updateAllocation(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAllocation(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const allocationIds = row.allocationId || this.ids;
      this.$modal.confirm('是否确认删除资金拨款记录编号为"' + allocationIds + '"的数据项？').then(function() {
        return delAllocation(allocationIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('funding/allocation/export', {
        ...this.queryParams
      }, `allocation_${new Date().getTime()}.xlsx`)
    },

  //查看历史记录
    handleHistory(row) {
      const allocationId = row.allocationId;
      if (!allocationId) {
        this.$message.error('参数无效');
        return;
      }
      getAllocationHistory(allocationId).then(response => {
        if (response.code === 200) {
          this.historyDialogVisible = true;
          this.historyList = response.data;

          // 在获取到历史记录后映射资金来源名称
          this.historyList = this.historyList.map(item => {
            item.sourceName = this.getSourceNameById(item.sourceId) || '未知';
            return item;
          });

          
        } else {
          this.$message.error(response.msg);
        }
      }).catch(error => {
        console.error(error);
        this.$message.error('查询历史记录失败');
      });
    },

    // 根据sourceId获取sourceName
    getSourceNameById(sourceId) {
      const source = this.sourceOptions.find(option => option.sourceId === sourceId);
      return source ? source.sourceName : null;
    },
      // 恢复数据
restoreRow(row) {
    // 弹出确认框
    this.$confirm('确定要还原该数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
    .then(() => {
        // 用户点击“确定”，调用后端接口恢复数据
        restoreData(row)
            .then(response => {
                if (response.code === 200) {
                    // 数据恢复成功后，刷新历史记录列表
                    console.log('row 信息:', row);
                    this.historyDialogVisible = false;
                    this.getList(); // 刷新列表
                    this.$message.success('数据还原成功');
                } else {
                    this.$message.error('数据还原失败');
                }
            })
            .catch(error => {
                console.error('数据还原失败', error);
                this.$message.error('还原失败');
            });
    })
    .catch(() => {
        // 用户点击“取消”，不执行任何操作
        this.$message.info('已取消还原');
    });
},

    // 判断是否有权限（注释掉，后续需要时启用）
    // hasPermission(permission) {
    //     const permissions = this.$store.state.user.permissions; // 从 Vuex 中获取权限列表
    //     return permissions.includes(permission);
    // },




  }
};
</script>

<style scoped>
.custom-dialog {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.table-header {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
}

.table-cell {
  color: #606266;
}

.file-link {
  color: #409EFF;
  text-decoration: underline;
}

.file-link:hover {
  color: #66b1ff;
}

.close-button {
  background-color: #409EFF;
  color: white;
  border: none;
}

.close-button:hover {
  background-color: #66b1ff;
}
</style>
